using System;
using Caliburn.Micro;
using MediaOwl.Common.ViewModels;

namespace MediaOwl.Common.Busy
{
    public class ShowBusy : IResult
    {
        private readonly IBusyCapable parent;
        private readonly bool notBusy;
        private readonly double targetValue;
        private IBusy busy;
        private Action<IBusy> onConfigure;

        public ShowBusy(IBusyCapable target)
        {
            parent = target;
            targetValue = 0;
            notBusy = false;
        }

        public ShowBusy(IBusyCapable target, double targetValue)
        {
            parent = target;
            this.targetValue = targetValue;
            notBusy = false;
        }

        public ShowBusy(IBusyCapable target, bool notBusy)
        {
            parent = target;
            this.notBusy = notBusy;
        }

        public ShowBusy Configured(Action<IBusy> configure)
        {
            onConfigure = configure;
            return this;
        }

        public void Execute(ActionExecutionContext context)
        {
            if (notBusy)
            {
                parent.HideBusy();
                Completed(this, new ResultCompletionEventArgs());
                return;
            }

            busy = parent.IsBusy 
                ? parent.CurrentBusyViewModel 
                : IoC.Get<DialogBusyViewModel>();
           
            if (onConfigure != null)
                onConfigure(busy);

            busy.WithTargetValue(targetValue);

            parent.ShowBusy(busy);

            Completed(this, new ResultCompletionEventArgs());
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}